import { defineStore } from "pinia"
import { ref, computed } from "vue"
import { pinia } from "@/pinia"
import { ElMessage } from "element-plus"
import type * as Football from "@/pages/europe/apis/type"
import { getMatchPredictEurope168Api, getHistoricalSimilarStatsApi, getColdPlayAnalysisStatsApi, getHistoricalSameOddsApi, getTeamStrengthAnalysisApi } from "@/pages/europe/apis"

export const useMatchPredictStore = defineStore("matchPredict", () => {
  // 状态
  const isLoading = ref(false)
  const matchPredictData = ref<Football.MatchPredictEurope168[]>([])
  const pagination = ref({
    current_page: 1,
    page_size: 20,
    total: 0
  })
  const searchCondition = ref<Football.MatchPredictEurope168Condition>({
    current_page: 1,
    page_size: 20
  })
  
  // 爆冷分析状态
  const coldPlayAnalysisLoadingStates = ref<Record<number, boolean>>({})
  const coldPlayAnalysisDataMap = ref<Record<number, { home: Football.ColdPlayAnalysisStats | null, away: Football.ColdPlayAnalysisStats | null }>>({})
  
  // 历史同赔数据状态
  const historicalSameOddsLoading = ref(false)
  const historicalSameOddsData = ref<Football.HistoricalSameOddsData[]>([])
  const historicalSameOddsPagination = ref({
    current_page: 1,
    page_size: 20,
    total: 0
  })
  const historicalSameOddsSearchCondition = ref<Football.HistoricalSameOddsCondition>({
    current_page: 1,
    page_size: 20
  })
  
  // 同赔分析状态
  const sameOddsAnalysisLoadingStates = ref<Record<number, boolean>>({})
  const sameOddsAnalysisDataMap = ref<Record<number, Football.SameOdds168AnalysisStats>>({})
  
  // 当前选中的比赛数据（用于同赔分析页面）
  const currentMatchForAnalysis = ref<Football.HistoricalSameOddsData | null>(null)
  
  // 队伍实力分析状态
  const teamStrengthAnalysisLoadingStates = ref<Record<number, boolean>>({})
  const teamStrengthAnalysisDataMap = ref<Record<number, { home: Football.TeamStrengthAnalysisData | null, away: Football.TeamStrengthAnalysisData | null }>>({})

  // 方法
  /** 查询欧洲赔率预测数据 */
  async function fetchMatchPredictEurope168() {
    try {
      isLoading.value = true
      const response = await getMatchPredictEurope168Api(searchCondition.value)
      
      if (response.code === 0) {
        // 确保正确赋值数据
        matchPredictData.value = response.data || []
        // 更新分页信息
        if (response.pagination) {
          pagination.value = {
            current_page: response.pagination.current_page,
            page_size: response.pagination.page_size,
            total: response.pagination.total
          }
        }
      } else {
        ElMessage.error(response.message || '查询失败')
      }
    } catch (error) {
      console.error('查询欧洲赔率预测数据失败:', error)
      ElMessage.error('查询失败，请稍后重试')
    } finally {
      isLoading.value = false
    }
  }

  /** 重置搜索条件 */
  function resetSearchCondition() {
    searchCondition.value = {
      current_page: 1,
      page_size: 20
    }
    matchPredictData.value = []
    pagination.value = {
      current_page: 1,
      page_size: 20,
      total: 0
    }
  }

  /** 更新搜索条件并查询 */
  function updateSearchCondition(condition: Partial<Football.MatchPredictEurope168Condition>) {
    searchCondition.value = {
      ...searchCondition.value,
      ...condition
    }
    fetchMatchPredictEurope168()
  }

  /** 获取历史同概统计数据 */
  async function fetchHistoricalSimilarStats(row: Football.MatchPredictEurope168) {
    try {
      // 构造请求参数，将当前行的胜负平概率每个值增减0.05作为最大最小参数
      const requestData = {
        prob_home_win_min: row.prob_home_win !== null ? row.prob_home_win - 0.005 : null,
        prob_home_win_max: row.prob_home_win !== null ? row.prob_home_win + 0.005 : null,
        prob_draw_min: row.prob_draw !== null ? row.prob_draw - 0.001 : null,
        prob_draw_max: row.prob_draw !== null ? row.prob_draw + 0.001 : null,
        prob_away_win_min: row.prob_away_win !== null ? row.prob_away_win - 0.005 : null,
        prob_away_win_max: row.prob_away_win !== null ? row.prob_away_win + 0.005 : null
      }

      const response = await getHistoricalSimilarStatsApi(requestData)
      
      if (response.code === 0 && response.data) {
        return response.data
      } else {
        ElMessage.error(response.message || '获取历史同概统计数据失败')
        return null
      }
    } catch (error) {
      console.error('获取历史同概统计数据失败:', error)
      ElMessage.error('获取历史同概统计数据失败，请稍后重试')
      return null
    }
  }

  /** 获取爆冷分析统计数据 */
  async function fetchColdPlayAnalysisStats(row: Football.MatchPredictEurope168) {
    try {
      // 设置加载状态
      const fid = row.fid || -1;
      coldPlayAnalysisLoadingStates.value[fid] = true;
      
      // 获取主队爆冷分析数据
      const homeRequestData = {
        teamid: row.homeid || null,
        match_date: row.matchtime ? row.matchtime.split(' ')[0] : null,
        season_id: row.season_id || null
      };
      
      const homeResponse = await getColdPlayAnalysisStatsApi(homeRequestData);
      
      // 获取客队爆冷分析数据
      const awayRequestData = {
        teamid: row.awayid || null,
        match_date: row.matchtime ? row.matchtime.split(' ')[0] : null,
        season_id: row.season_id || null
      };
      
      const awayResponse = await getColdPlayAnalysisStatsApi(awayRequestData);
      
      if (homeResponse.code === 0 && awayResponse.code === 0) {
        // 保存主队和客队的爆冷分析数据
        coldPlayAnalysisDataMap.value[fid] = {
          home: homeResponse.data,
          away: awayResponse.data
        };
        
        return coldPlayAnalysisDataMap.value[fid];
      } else {
        const errorMessage = homeResponse.message || awayResponse.message || '获取爆冷分析统计数据失败';
        ElMessage.error(errorMessage);
        return null;
      }
    } catch (error) {
      console.error('获取爆冷分析统计数据失败:', error);
      ElMessage.error('获取爆冷分析统计数据失败，请稍后重试');
      return null;
    } finally {
      // 清除加载状态
      const fid = row.fid || -1;
      coldPlayAnalysisLoadingStates.value[fid] = false;
    }
  }

  /** 查询历史同赔数据 */
  async function fetchHistoricalSameOdds() {
    try {
      historicalSameOddsLoading.value = true
      const response = await getHistoricalSameOddsApi(historicalSameOddsSearchCondition.value)
      
      if (response.code === 0) {
        historicalSameOddsData.value = response.data || []
        // 更新分页信息
        if (response.pagination) {
          historicalSameOddsPagination.value = {
            current_page: response.pagination.current_page,
            page_size: response.pagination.page_size,
            total: response.pagination.total
          }
        }
      } else {
        ElMessage.error(response.message || '查询历史同赔数据失败')
      }
    } catch (error) {
      console.error('查询历史同赔数据失败:', error)
      ElMessage.error('查询历史同赔数据失败，请稍后重试')
    } finally {
      historicalSameOddsLoading.value = false
    }
  }

  /** 重置历史同赔搜索条件 */
  function resetHistoricalSameOddsSearchCondition() {
    historicalSameOddsSearchCondition.value = {
      current_page: 1,
      page_size: 20
    }
    historicalSameOddsData.value = []
    historicalSameOddsPagination.value = {
      current_page: 1,
      page_size: 20,
      total: 0
    }
  }

  /** 更新历史同赔搜索条件并查询 */
  function updateHistoricalSameOddsSearchCondition(condition: Partial<Football.HistoricalSameOddsCondition>) {
    historicalSameOddsSearchCondition.value = {
      ...historicalSameOddsSearchCondition.value,
      ...condition
    }
    fetchHistoricalSameOdds()
  }

  /** 设置当前选中的比赛数据 */
  function setCurrentMatchForAnalysis(match: Football.HistoricalSameOddsData | null) {
    currentMatchForAnalysis.value = match
  }

  /** 获取队伍实力分析数据 */
  async function fetchTeamStrengthAnalysis(row: Football.MatchPredictEurope168 | Football.HistoricalSameOddsData) {
    try {
      // 设置加载状态
      const fid = row.fid || -1;
      teamStrengthAnalysisLoadingStates.value[fid] = true;
      
      // 获取主队实力分析数据
      const homeRequestData = {
        teamid: row.homeid || 0
      };
      
      const homeResponse = await getTeamStrengthAnalysisApi(homeRequestData);
      
      // 获取客队实力分析数据
      const awayRequestData = {
        teamid: row.awayid || 0
      };
      
      const awayResponse = await getTeamStrengthAnalysisApi(awayRequestData);
      
      if (homeResponse.code === 0 && awayResponse.code === 0) {
        // 保存主队和客队的实力分析数据
        teamStrengthAnalysisDataMap.value[fid] = {
          home: homeResponse.data,
          away: awayResponse.data
        };
        
        return teamStrengthAnalysisDataMap.value[fid];
      } else {
        const errorMessage = homeResponse.message || awayResponse.message || '获取队伍实力分析数据失败';
        ElMessage.error(errorMessage);
        return null;
      }
    } catch (error) {
      console.error('获取队伍实力分析数据失败:', error);
      ElMessage.error('获取队伍实力分析数据失败，请稍后重试');
      return null;
    } finally {
      // 清除加载状态
      const fid = row.fid || -1;
      teamStrengthAnalysisLoadingStates.value[fid] = false;
    }
  }

  /** 获取队伍实力分析数据（用于同赔分析页面） */
  async function fetchTeamStrengthAnalysisForSameOdds(match: Football.HistoricalSameOddsData) {
    try {
      // 设置加载状态
      const fid = match.fid || -1;
      teamStrengthAnalysisLoadingStates.value[fid] = true;
      
      // 获取主队实力分析数据
      const homeRequestData = {
        teamid: match.homeid || 0
      };
      
      const homeResponse = await getTeamStrengthAnalysisApi(homeRequestData);
      
      // 获取客队实力分析数据
      const awayRequestData = {
        teamid: match.awayid || 0
      };
      
      const awayResponse = await getTeamStrengthAnalysisApi(awayRequestData);
      
      if (homeResponse.code === 0 && awayResponse.code === 0) {
        // 保存主队和客队的实力分析数据
        teamStrengthAnalysisDataMap.value[fid] = {
          home: homeResponse.data,
          away: awayResponse.data
        };
        
        return teamStrengthAnalysisDataMap.value[fid];
      } else {
        const errorMessage = homeResponse.message || awayResponse.message || '获取队伍实力分析数据失败';
        ElMessage.error(errorMessage);
        return null;
      }
    } catch (error) {
      console.error('获取队伍实力分析数据失败:', error);
      ElMessage.error('获取队伍实力分析数据失败，请稍后重试');
      return null;
    } finally {
      // 清除加载状态
      const fid = match.fid || -1;
      teamStrengthAnalysisLoadingStates.value[fid] = false;
    }
  }

  return {
    // 状态
    isLoading,
    matchPredictData,
    pagination,
    searchCondition,
    
    // 爆冷分析状态
    coldPlayAnalysisLoadingStates,
    coldPlayAnalysisDataMap,
    
    // 历史同赔数据状态
    historicalSameOddsLoading,
    historicalSameOddsData,
    historicalSameOddsPagination,
    historicalSameOddsSearchCondition,
    
    // 同赔分析状态
    sameOddsAnalysisLoadingStates,
    sameOddsAnalysisDataMap,
    currentMatchForAnalysis,
    
    // 队伍实力分析状态
    teamStrengthAnalysisLoadingStates,
    teamStrengthAnalysisDataMap,
    
    // 计算属性
    currentPage: computed(() => pagination.value.current_page),
    total: computed(() => pagination.value.total),
    historicalSameOddsCurrentPage: computed(() => historicalSameOddsPagination.value.current_page),
    historicalSameOddsTotal: computed(() => historicalSameOddsPagination.value.total),
    
    // 方法
    fetchMatchPredictEurope168,
    resetSearchCondition,
    updateSearchCondition,
    fetchHistoricalSimilarStats,
    fetchColdPlayAnalysisStats,
    fetchHistoricalSameOdds,
    resetHistoricalSameOddsSearchCondition,
    updateHistoricalSameOddsSearchCondition,
    setCurrentMatchForAnalysis,
    fetchTeamStrengthAnalysis,
    fetchTeamStrengthAnalysisForSameOdds
  }
})

export function useMatchPredictStoreOutside() {
  return useMatchPredictStore(pinia)
}
